package com.kkb.util;

import com.alibaba.druid.pool.DruidDataSource;

import java.sql.*;
import java.util.List;
import java.util.ResourceBundle;

/**
 * 基本的数据库操作
 */
public class DBUtils {
    // 数据库连接配置参数
    private static String driver;//驱动类路径
    private static String url;//数据库连接字符串
    private static String username;//用户名
    private static String password;//密码

    // 数据库连接池-Druid
    private static DruidDataSource dataSource = new DruidDataSource();

    static {
        // 加载配置参数
        ResourceBundle db = ResourceBundle.getBundle("db");
        driver = db.getString("driver");
        url = db.getString("url");
        username = db.getString("username");
        password = db.getString("password");

        // 配置Druid
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
    }

    /**
     * 获取数据库连接
     *
     * @return 连接
     */
    public static Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 关闭资源
     *
     * @param conn 连接
     * @param stmt 状态通道
     * @param rs   结果集
     */
    public static void close(Connection conn, Statement stmt, ResultSet rs) {
        try {
            if (rs != null) {//如果返回的结果集对象不能为空,就关闭连接
                rs.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (stmt != null) {
                stmt.close();//关闭预编译对象
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (conn != null) {
                conn.close();//关闭结果集对象
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置参数
     */
    public static void setParam(PreparedStatement ps, List<Object> list) throws SQLException {
        int index = 1;
        for (Object o : list) {
            ps.setObject(index++, o);
        }
    }
}
